var UranusWei = angular.module("UranusWei");

(function (ng) {
    var DONT_ENUM = "propertyIsEnumerable,isPrototypeOf,hasOwnProperty,toLocaleString,toString,valueOf,constructor".split(","),
        hasOwn = ({}).hasOwnProperty;
    for (var i in {
        toString: 1
    }) {
        DONT_ENUM = false;
    }
    Object.keys = Object.keys || (function (obj) { //ecma262v5 15.2.3.14
        return function (obj) {
            var result = [],
                key;
            for (key in obj) {
                if (hasOwn.call(obj, key)) {
                    result.push(key);
                }
            }
            if (DONT_ENUM && obj) {
                for (var i = 0; i < DONT_ENUM.length; i++) {
                    key = DONT_ENUM[i++];
                    if (hasOwn.call(obj, key)) {
                        result.push(key);
                    }
                }
            }
            return result;
        };
    })();

    function _setConfig(moduleConfig) {

        return function (cfg) {
            if (!ng.isDefined(cfg)) return;

            ng.forEach(Object.keys(moduleConfig), function () {
                if (cfg.hasOwnProperty(key)) {
                    moduleConfig[key] = cfg[key] + '';
                }
            });
        }
    }

    var moveDefaultConfig = {
        time: 3000, //循环执行间隔
        moveNg: "adInfo",
        moveRadius: "radius"
    };


    UranusWei.provider('moveConfig', [function () {
        var moduleConfig = ng.copy(moveDefaultConfig);
        var result = {
            $set: _setConfig(moduleConfig),
            $get: function () {
                return moduleConfig;
            }
        }
        return result;
    }]);

}(angular));

/* 自动聚焦 */
UranusWei.directive('setFocus', [function () {
    return function (scope, element) {
        element[0].focus();
    };
}]);

UranusWei.factory('translider', ['$timeout', '$rootScope', 'appconfig', function ($timeout, $rootScope, appconfig) {
    var transform = {}, _this, startPos = {}, movePos = {}, startTouchTime, timer;
    var isMove = true;
    var transform = function (options) {
        var _this = this;
        _this.startPos = {};
        _this.movePos = {};
        _this.startTouchTime = null;
        _this.timer = null;
        _this.element = options.element;
        _this.isloop = options.isloop; //是否自动轮播
        _this.size = options.size;
        _this.index = options.isloop ? 1 : 1;
        if (options.speed == 0) { //安全页面第一张到最后一张出现白页问题
            _this.index = 0;
        }
        _this.islider = typeof options.islider === "undefined" ? true : false; //是否无限轮询播放
        _this.innerWidth = window.innerWidth;
        _this.speed = options.speed;  //为0就不自动轮播
        if (!_this.speed || options.speed == 0) {
            _this.speed = 3000;  //原3000
        }
        if (options.cbEnd) {
            _this.cbEnd = options.cbEnd;
        } //是否循环
        _this.cancel();
        _this.play();
        _this.isMove = true;
        _this.move = false;
        _this.element.off("touchstart mousedown");
        _this.element.on("touchstart mousedown", function (e) {
            _this.touchStart.apply(_this, [e]);
        });

        _this.cssTransition = "all 0.3s ease";
        _this.transformx = 0;

    };

    transform.prototype.play = function () {
        var _this = this;
        if (_this.size <= 1 || !this.isloop) return;
        _this.cancel();
        if (_this.speed > 0) {
            _this.timer = $timeout(function () {
                _this.setIndex("left");
                _this.transitionEnd();
                _this.setElementTransform(-_this.innerWidth, true, false, true);
                _this.play();
            }, _this.speed);
            $rootScope.djsArr.push(_this.timer);
        }
    }

    transform.prototype.getCoordinates = function (event) {
        var touches = event.touches && event.touches.length ? event.touches : [event];
        var e = (event.changedTouches && event.changedTouches[0]) ||
            (event.originalEvent && event.originalEvent.changedTouches &&
                event.originalEvent.changedTouches[0]) ||
            touches[0].originalEvent || touches[0];
        return {
            pageX: e.clientX,
            pageY: e.clientY
        };
    }
    transform.prototype.cancel = function () {
        var _this = this;
        _this.timer && $timeout.cancel(_this.timer);
    };
    transform.prototype.touchStart = function (e) {
        var _this = this;
        if (!_this.isMove) {
            return;
        }
        _this.isMove = false;
        _this.move = false;
        _this.cancel();
        var touch = _this.getCoordinates(e); //e.targetTouches[0];
        _this.setStartPostions(touch);
        movePos = { x: 0, y: 0 };
        _this.element.on("touchmove mousemove", function (e) {
            _this.touchMove.apply(_this, [e]);
        });
        _this.element.on("touchend mouseup", function (e) {
            _this.touchEnd.apply(_this, [e]);
        });
        _this.startTouchTime = new Date();
        _this.transformx = _this.getTranslate3dX();
    };

    transform.prototype.touchMove = function (e) {
        // if (!_this.isMove) {
        //     return;
        // }
        var touches = e.touches && e.touches.length ? e.touches : [e];
        if (touches.length > 1) {
            return;
        }
        var _this = this;
        var touch = _this.getCoordinates(e);
        if (touch.length > 1) { //防止双手touch
            _this.cancelTouch();
            return;
        }
        _this.move = true;
        _this.setMovePostions(touch);
        _this.setElementTransform(_this.movePos.x);

        if (e.preventDefault) e.preventDefault();
        else e.returnValue = false;
    };
    transform.prototype.touchEnd = function () {
        var _this = this;
        if (_this.size == 0 || !_this.move) {
            return;
        }
        var touchEndTime = Date.now();
        var timeDiff = touchEndTime - _this.startTouchTime;
        var moveNum = 0;
        if (_this.size > 1 && ((timeDiff < 300 && _this.movePos.x != 0) || (Math.abs(_this.movePos.x) > _this.innerWidth / 2))) {
            if (_this.movePos.x < 0) {	//向左滑动
                if (!_this.islider && (_this.index == _this.size - 1)) {
                    moveNum = 0;
                } else {
                    moveNum = -_this.innerWidth;
                    _this.setIndex('left');
                }
            } else {
                if (!_this.islider && (_this.index == 0)) {
                    moveNum = 0;
                } else {
                    moveNum = _this.innerWidth;
                    _this.setIndex("right");
                }
            }
            _this.transitionEnd();
        } else {
            _this.isMove = true;
        }
        _this.setElementTransform(moveNum, true);
        _this.element.off("touchmove mousemove");
        _this.element.off("touchend mouseup");
        _this.isloop && _this.play();
    };

    transform.prototype.transitionEnd = function () {
        var _this = this;
        typeof _this.cbEnd === "function" && _this.cbEnd(_this.index);
        var timems = 300;
        _this.isMove = !(_this.index == 1 || _this.index == _this.size - 2);
        $timeout(function () {
            if (_this.index == 1) {
                _this.setElementTransform(-(this.innerWidth), false, true);
            } else if (_this.index == _this.size - 2) {
                _this.setElementTransform(-((this.innerWidth) * _this.index), false, true);
            }
            _this.isMove = true;
        }, timems);
    };

    transform.prototype.setIndex = function (dir) {
        var _this = this;
        if (!_this.islider) {
            if (dir == 'left') {
                _this.index = _this.index == _this.size ? _this.size : _this.index + 1;
            } else {
                _this.index = _this.index == 0 ? 0 : _this.index - 1;
            }
        } else {
            if (dir == 'left') {
                _this.index = _this.index == _this.size - 2 ? 1 : _this.index + 1;
            } else {
                _this.index = _this.index == 1 ? this.size - 2 : _this.index - 1;
            }
        }
    };
    transform.prototype.setElementTransform = function (move, isTransition, isEnd, isPlay) {
        var _this = this;
        var transformx = 0;
        if (isPlay) {
            transformx = _this.getTranslate3dX();
        } else if (!isEnd) {
            transformx = _this.transformx;
        }
        var moveX = transformx + move;
        if (!isTransition) {
            _this.setTransitionAndTransform('none', 'translate3d(' + moveX + 'px,0px,0px)');
        } else {
            _this.setTransitionAndTransform('translate3d(' + moveX + 'px,0px,0px)');
        }

    };

    transform.prototype.cancelTouch = function () {
        var _this = this;
        _this.element.off("touchstart mousedown");
        _this.element.off("touchmove mousemove");
        _this.element.off("touchend mouseup");
    };

    transform.prototype.setTransitionAndTransform = function (transitionCss, transformCss) {
        var _this = this;
        if (!transformCss) {
            transformCss = transitionCss;
            transitionCss = _this.cssTransition;
        }
        _this.element.css("-webkit-transition", transitionCss).css("transition", transitionCss);
        _this.element.css("-webkit-transform", transformCss).css("transform", transformCss);
    }

    transform.prototype.setStartPostions = function (touch) {
        var _this = this;
        _this.startPos.x = touch.pageX;
        _this.startPos.y = touch.pageY;
    }

    transform.prototype.setMovePostions = function (touch) {
        var _this = this;
        _this.movePos.x = touch.pageX - _this.startPos.x;
        _this.movePos.y = touch.pageY - _this.startPos.y;
    }

    transform.prototype.getTranslate3dX = function () {
        var _this = this;
        var transform = _this.element.css("transform");
        if (!transform) return 0;
        var styletrans = transform.replace("translate3d", "");
        var trans = styletrans.split(',');
        return parseFloat(trans[0].replace("(", "").replace("px", ""));

    }

    return transform;
}]);

// UranusWei.directive('productMove', [
//     '$timeout', '$rootScope', 'translider', 'appconfig',
//     function ($timeout, $rootScope, translider, appconfig) {
//         return {
//             restrict: 'A',
//             transclude: true,
//             scope: {
//                 ngModel: "=",
//                 active: "=",
//             },
//             link: function (scope, element, attrs) {
//                 var innerWidth = window.innerWidth;
//                 scope.$watch('active', function (active) {
//                     if (active && scope.ngModel.length > 1) {
//                         resetModel();
//                         setElementCss();
//                         var options = {
//                             element: element,
//                             size: scope.ngModel.length,
//                             speed: appconfig.speedconfig.producthomebanner,
//                             isloop: appconfig.loopconfig.produchomebannerloop
//                         }
//                         $rootScope.trans = new translider(options);
//                     }
//                 });
//                 function setElementCss() {
//                     element.css("width", scope.ngModel.length * (innerWidth) + "px");
//                     element.css("-webkit-transform", "translate3d(-" + (innerWidth) + "px,0px,0px)");
//                     element.css("transform", "translate3d(-" + (innerWidth) + "px,0px,0px)");
//                 }
//                 function resetModel() {
//                     if (scope.ngModel && scope.ngModel.length > 1) {
//                         var len = scope.ngModel.length;
//                         var first = angular.copy(scope.ngModel[0]);
//                         var last = angular.copy(scope.ngModel[len - 1]);
//                         scope.ngModel.push(first);
//                         scope.ngModel.splice(0, 0, last);
//                     }
//                 }
//             }

//         }
//     }]);



UranusWei.directive('productMo', ['$timeout',
    function swipers($timeout) {
        return {
            restrict: "A",
            scope: {
                ngModel: "=",
                active: "=",
                productUrl: "&"
            },
            link: function (scope, element, attrs) {
                scope.$watch('active', function (active) {
                    if (active && scope.ngModel.length > 0) {
                        var swiper = new iSlider({
                            data: scope.ngModel,
                            dom: document.getElementById("animation-effect"),
                            type: 'dom',
                            productUrl:scope.productUrl(),
                            duration: 2000,
                            animateType: 'depth',
                            isAutoplay: false,
                            isLooping: true,
                        });
                    }
                });
            }
        };
    }
]);


/* banner图轮播 */
UranusWei.directive('adMove', ['$timeout', '$rootScope', 'translider', 'appconfig',
    function ($timeout, $rootScope, translider, appconfig) {
        return {
            restrict: 'A',
            transclude: true,
            scope: {
                ngModel: "=",
                active: "=",
                transitionEnd: "&"
            },
            link: function (scope, element, attr) {
                var innerWidth = window.innerWidth;
                scope.$watch('active', function (active) {
                    if (active && scope.ngModel.length > 0) {
                        resetModel();
                        setElementCss();
                        var options = {
                            element: element,
                            size: scope.ngModel.length,
                            speed: appconfig.speedconfig.produthome,
                            cbEnd: scope.transitionEnd(),
                            isloop: appconfig.loopconfig.produthomeloop
                        }
                        new translider(options);
                        //translider.init(element, scope.ngModel.length, 5000, scope.transitionEnd());
                    }
                });
                function setElementCss() {
                    element.css("height", innerWidth / 750 * 300 + "px");
                    if (window.location.pathname == '/mine/more') {
                        element.css("height", innerWidth / 640 * 225 + "px");
                    } else if (window.location.pathname == '/mine/withdrawals') {
                        element.css("height", innerWidth / 690 * 120 + "px");
                    }
                    if (scope.ngModel.length > 1) {
                        element.css("-webkit-transform", "translate3d(-" + innerWidth + "px,0px,0px)");
                        element.css("transform", "translate3d(-" + innerWidth + "px,0px,0px)");
                    } else {
                        element.css("-webkit-transform", "translate3d(0px,0px,0px)");
                        element.css("transform", "translate3d(0px,0px,0px)");
                    }
                }
                function resetModel() {
                    if (scope.ngModel && scope.ngModel.length > 1) {
                        var len = scope.ngModel.length;
                        var first = angular.copy(scope.ngModel[0]);
                        var last = angular.copy(scope.ngModel[len - 1]);
                        scope.ngModel.push(first);
                        scope.ngModel.splice(0, 0, last);
                    }
                }
            }
        }
    }
]);

/*html渲染*/
angular.module("UranusWei").filter('trustHtml', ['$sce', function ($sce) {
    return function (input) {
        if (input) {
            input = input.replace("href=\"http", "h=\"http"); //去掉图片链接 
        }
        return $sce.trustAsHtml(input);
    }
}]);

/*日期显示*/
angular.module("UranusWei").filter('datebFormat', ['$sce', function ($sce) {
    return function (input,param) {
        if(!input){
            return
        }
        var input = new Date(input.replace(/-/g, '/'));
        year = input.getFullYear()
        month = input.getMonth()+1
        day = input.getDate()
        hour = input.getHours()
        minute = input.getMinutes()
        // 好友列表日期展示（2018年3月13日注册）
        // 奖金明细日期展示（2018年3月13日注册）
        if(param == 'friend'){
            input = year+'年'+month+"月"+day+'日注册'
        }else if(param == 'active'){
            input = year+'年'+month+"月"+day+'日'
        }
        return input
    }
}]);

/*银行限额转化*/
angular.module("UranusWei").filter('rmbFormat', ['$sce', function ($sce) {
    return function (input,param) {
        if(!param){
            param = "万"
        }
        if (input>9999) {
           input = input/10000+param
        }
        return input
    }
}]);
/*首字母大写*/
angular.module("UranusWei").filter('upperFirst', ['$sce', function ($sce) {
    return function (input) {
        input =  input.substring(0,1).toUpperCase()+input.substring(1);//处理name值首字母大写
        return input
    }
}]);

/*隐藏身份证或手机号*/
angular.module("UranusWei").filter('hideidcard', function () {
    return function (input) {
        var newvalue = "";
        if (input) {
            input = input.toString();
            for (var i = 0; i < input.length; i++) {
                if (i < 3) {
                    newvalue = newvalue + input[i];
                } else if (i >= input.length - 4) {
                    newvalue = newvalue + input[i];
                } else {
                    newvalue = newvalue + "*";
                }
            }
        }
        return newvalue;
    }
});
/*数组去重*/
angular.module("UranusWei").filter('unique', function () {
    return function (collection, keyname) {
        var output = [],
            keys = [];

        angular.forEach(collection, function (item) {
            var key = item[keyname];
            if (keys.indexOf(key) === -1) {
                keys.push(key);
                output.push(item);
            }
        });

        return output;
    };
});

/*年利率精确小数*/
angular.module("UranusWei").filter('AnnualRateOfYear', function () {
    return function (annual) {
        annual = isNaN(annual) ? 0.00 : annual;
        if (!annual) {
            return annual;
        }
        annual = parseFloat(parseFloat(annual).toPrecision(4));
        return annual;
    }
});

//产品倒计时
angular.module("UranusWei").filter('ProductDate', ['$sce', function ($sce) {
    return function (input) {
        input = parseInt(input, 10);
        var day = 0, hour = 0, min = 0, sec = 0;
        input = parseInt(input / 1000, 10);
        hour = parseInt(input / 3600, 10);
        input = input % 3600;
        min = parseInt(input / 60, 10);
        sec = input % 60;
        if (hour < 10) {
            hour = "0" + hour;
        }
        if (min < 10) {
            min = "0" + min;
        }
        if (sec < 10) {
            sec = "0" + sec;
        }
        var returnDate = hour + ":" + min + ":" + sec;
        return returnDate;
    }
}]);
